package com.kotlin.demo

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.kotlin.demo.bean.ArticleData
import com.kotlin.demo.net.ApiResponse

import com.kotlin.demo.net.RetrofitClient
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis

/**
 * author : fang.zhang
 * e-mail : initzf@126.com
 * date   : 2019-11-19
 * desc   :
 */

class UserViewModel : ViewModel() {

    val TAG = "UserViewModel"

    val datas: MutableLiveData<ApiResponse<ArticleData>> by lazy { MutableLiveData<ApiResponse<ArticleData>>().also { getData() } }


    /**
     * 这是一种方式 ，直接在activity到 顶级协程中拿到值
     */
    suspend fun test233(): ArticleData? {
        return viewModelScope.async {
            val data = call {
                RetrofitClient.api.getData1()
            }
            //表示有异常
            if (data.code == ApiResponse.ERROR_CODE) {
                Log.i(CommViewModel2.TAG, ": ${data.msg}")
                return@async null
            }
            //取出我们后台接口返回的数据
            data.body
        }.await()
    }


    /**
     *  网络请求
     */
    private fun getData() {
        viewModelScope.launch {
            val data = call {
                RetrofitClient.api.getData1()
            }
            datas.value = data;
        }
    }

    override fun onCleared() {
        super.onCleared()

        viewModelScope.coroutineContext.cancelChildren()
    }
}